package com.zhsm.fuxi.mvp.ui.activitys

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Message
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AnticipateInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.alipay.sdk.app.PayTask
import com.baidu.location.BDLocation
import com.baidu.mapapi.map.*
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener.REASON_GESTURE
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.utils.DistanceUtil
import com.hankkin.reading.base.TakePhotoMvpActivity
import com.hankkin.reading.control.OrderControl
import com.hankkin.reading.control.UserControl
import com.hankkin.reading.event.EventMap
import com.zhsm.fuxi.R
import com.zhsm.fuxi.app.Constant
import com.zhsm.fuxi.bean.*
import com.zhsm.fuxi.control.AppManager
import com.zhsm.fuxi.mapmanager.MapLoader
import com.zhsm.fuxi.mapmanager.MapStrategy.LocationCallBack
import com.zhsm.fuxi.mapmanager.MapStrategy.MyOnMapStatusChangeListener
import com.zhsm.fuxi.mapmanager.MapStrategy.OnOrientationListener
import com.zhsm.fuxi.mapmanager.mark.MarkConfig
import com.zhsm.fuxi.mvp.contract.MainContract
import com.zhsm.fuxi.mvp.presenter.MainPresenter
import com.zhsm.fuxi.mvp.ui.adapter.ChoseCarRecyclerAdapter
import com.zhsm.fuxi.mvp.ui.dialog.*
import com.zhsm.fuxi.utils.CommonUtils
import com.zhsm.fuxi.utils.GlideUtils
import com.zhsm.fuxi.utils.QiniuUpLoadHelper
import com.zhsm.fuxi.utils.TimeUtils
import com.zhsm.fuxi.view.recycler.ScalableCardHelper
import com.zhsm.fuxi.view.widget.MyMapmarkerView
import com.zhsm.paipaiout.baselibrary.utils.AppUtils
import com.zhsm.paipaiout.baselibrary.utils.MyStatusBarUtil
import com.zhsm.paipaiout.baselibrary.utils.ToastUtils
import com.zhsm.paipaiout.baselibrary.utils.UIUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_chose_car.view.*
import kotlinx.android.synthetic.main.layout_drawer_header.view.*
import kotlinx.android.synthetic.main.layout_main_findcar.view.*
import kotlinx.android.synthetic.main.layout_main_pay.view.*
import kotlinx.android.synthetic.main.layout_main_usecar.view.*
import org.devio.takephoto.model.TResult
import org.jetbrains.anko.sdk25.coroutines.onClick
import java.lang.ref.WeakReference


class MainActivity : TakePhotoMvpActivity<MainPresenter>(), MainContract.IView, OnOrientationListener, LocationCallBack
        , BaiduMap.OnMarkerClickListener, ScalableCardHelper.OnPageChangeListener {

    companion object {
        private val SDK_PAY_FLAG = 1
    }
    private var mTimer: CountDownTimer? = null
    private var toast: Toast? = null
    private var carMaker: Marker? = null
    var mMainTakePicDialog: ReportsTakeCarDialog? = null
    var mReportsInteriorDialog: ReportsInteriorDialog? = null
    var mReportsBackCarDialog: ReportsBackCarDialog? = null
    val mBackCarErrorDialog by lazy { BackCarErrorDialog(this) }
    val mQiniuUpLoadHelper by lazy { QiniuUpLoadHelper(Constant.QiNiu.BUSINESS) }
    val UpdateVercionDialog by lazy { UpdateVercionDialog(this) }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun registerPresenter() = MainPresenter::class.java

    override fun isHasBus(): Boolean {
        return true
    }

    override fun isSupportSwipeBack(): Boolean {
        return false
    }

    override fun initView() {
        setStatuBar()
        initClickAndNav()
        initMapView()
        toast = Toast.makeText(applicationContext, "再按一次退出应用", Toast.LENGTH_SHORT)
    }

    override fun initData() {
        getPresenter().getDoingOrder()
        AppUtils.getVersionName(this)?.let {
            getPresenter().checkVersion(it, false)
        }
    }

    //更新底部布局
    override fun setTakeCarViews(stateStrId: OrderResp?) {
        hideLoding()
        if (stateStrId == null || stateStrId.state != Constant.ORDER.EXECUTING) {
            if (mainBottomView.visibility == View.VISIBLE) mainBottomView.visibility = View.GONE
            return
        }
        stateStrId?.run {
            OrderControl.setCurrentOrder(stateStrId)
            if (mainBottomView.childCount != 0) {
                mTimer?.cancel()
                mainBottomView.removeAllViews()
            }
            when (node) {
                Constant.CarState.TAKE_REPORT_SURFACE ,
                Constant.CarState.TO_TAKE_VEHICLE -> {
                    carMaker?.let {
                        it.isVisible = false
                        carMaker = null
                    }
                    if (expireMillis == null || expireMillis!! < 0) {
                        showLoding()
                        getPresenter().cancelOrder(id)
                        return
                    }
                   if (choseCarView.visibility == View.VISIBLE) choseCarView.visibility = View.GONE
                    //取车
                    val bottomView = LayoutInflater.from(this@MainActivity).inflate(R.layout.layout_main_findcar, mainBottomView, false)
                    bottomView.findCarBtmCancel.onClick {
                        showLoding()
                        getPresenter().cancelOrder(stateStrId.id)
                    }
                    bottomView.findCarBtmOk.onClick {
                        when(OrderControl.getCurrentOrder()?.node ){
                            Constant.CarState.TAKE_REPORT_SURFACE -> showTakePhotoView()
                            Constant.CarState.TO_TAKE_VEHICLE ->{
                                showLoding()
                                getPresenter().takeCar()
                            }
                        }
                    }
                    bottomView.findCarBtmDistance.onClick { ToastUtils.makeText("导航") }
                    bottomView.upPicAgain.onClick { showTakePhotoView() }
                    if (distance == 0) distance = DistanceUtil.getDistance(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()), LatLng(origin?.latitude!!, origin?.longitude!!)).toInt()
                    bottomView.findCarBtmDistance.text = "${distance}m"
                    bottomView.findCarBtmCarNum.text = vehicle?.plate
                    bottomView.findCarBtmCarDistance.text = "${vehicle?.mileage}km"
                    bottomView.findCarBtmDetTitle.text = origin?.name
                    bottomView.findCarBtmDetAdrs.text = origin?.address
                    startCountdown(expireMillis ?: 1, bottomView.findCarBtmTime)
                    mainBottomView.addView(bottomView)
                }
                Constant.CarState.TAKE_REPORT_INTERIOR,
                Constant.CarState.TO_RETURN_VEHICLE,
                Constant.CarState.RETURN_REPORT_SURFACE -> {  // 内饰报备，用车，还车
                    addCarMarker()
                    val bottomUseView = LayoutInflater.from(this@MainActivity).inflate(R.layout.layout_main_usecar, mainBottomView, false)
                    bottomUseView.useCarLockOpen.onClick {
                        showLoding()
                        getPresenter().openDoor(OrderControl.getId())
                    }
                    bottomUseView.useCarLockClose.onClick {
                        showLoding()
                        getPresenter().closeDoor(OrderControl.getId())
                    }
                    bottomUseView.useCarBlt.onClick {
                        ToastUtils.makeText("蓝牙")
                    }
                    bottomUseView.useCarBtmBack.onClick {
                        if (OrderControl.getCurrentOrder()?.node == Constant.CarState.RETURN_REPORT_SURFACE ||
                                OrderControl.getCurrentOrder()?.node == Constant.CarState.TAKE_REPORT_INTERIOR) {
                            if (mReportsBackCarDialog == null) {
                                mReportsBackCarDialog = ReportsBackCarDialog(this@MainActivity)
                                mReportsBackCarDialog!!.setOnClickTakePhoto(object : ReportsBackCarDialog.onClickBtn {
                                    override fun oNnext() {
                                        if (mReportsBackCarDialog!!.isOk()) {
                                            showLoding()
                                            getPresenter().postBackCarSurface(mReportsBackCarDialog!!.imagesUrl)
                                        }
                                    }
                                    override fun takePic() {
                                        picFromWhere = Constant.COMMON.TAKEPIC_BACKCAR_OUT
                                        takePicture()
                                    }

                                })
                            }
                            mReportsBackCarDialog!!.show()
                        } else if (node == Constant.CarState.TO_RETURN_VEHICLE){
                            showLoding()
                            getPresenter().backCar()
                        }
                    }
                    bottomUseView.useCarBtnMoney.text = "当前费用：${amount}元"
                    bottomUseView.useCarBtnDistance.text = "续航里程：${runMileage}km"
                    if (vehicle?.isSell == Constant.CAR.CAN_SELL) {
                        bottomUseView.useCarBtmCarSell.text = "售卖信息"
                        bottomUseView.useCarBtmCarSell.onClick {
                            ToastUtils.makeText("售卖信息")
                        }
                    } else {
                        bottomUseView.useCarBtmCarSell.text = "暂不可售"
                        bottomUseView.useCarBtmCarSell.onClick {
                            return@onClick
                        }
                    }
                    bottomUseView.useCarBtmCarNum.text = vehicle?.plate
                    mainBottomView.addView(bottomUseView)
                }
                Constant.CarState.TO_BE_PAID -> {
                    carMaker?.let {
                        it.isVisible = false
                        carMaker = null
                    }
                    val bottomPayView = LayoutInflater.from(this@MainActivity).inflate(R.layout.layout_main_pay, mainBottomView, false)
                    bottomPayView.mainPayMoney.text = "¥ $amount"
                    bottomPayView.mainPayBtn.text = "确认支付${amount}元"
                    bottomPayView.mainPayCarNum.text = "${vehicle?.plate}"
                    bottomPayView.mainPayUseDistance.text = "$runMileage km"
                    bottomPayView.mainPayCarTime.text = TimeUtils.getDistanceTime(chargeEndTime!!, chargeStartTime!!)
                    bottomPayView.mainPayStart.text = "${origin?.address}"
                    bottomPayView.mainPayEnd.text = "$destination"
                    bottomPayView.mainPayZfbCb.onClick {
                        bottomPayView.mainPayZfbCb.isChecked = true
                        bottomPayView.mainPayWeixin.isChecked = false
                    }
                    bottomPayView.mainPayWeixin.onClick {
                        bottomPayView.mainPayZfbCb.isChecked = false
                        bottomPayView.mainPayWeixin.isChecked = true
                    }
                    bottomPayView.mainPayZfb.onClick {
                        bottomPayView.mainPayZfbCb.isChecked = true
                        bottomPayView.mainPayWeixin.isChecked = false
                    }
                    bottomPayView.mainPayWx.onClick {
                        bottomPayView.mainPayZfbCb.isChecked = false
                        bottomPayView.mainPayWeixin.isChecked = true
                    }
                    bottomPayView.mainPayBtn.onClick {
                        if (bottomPayView.mainPayZfbCb.isChecked) {
                            id?.let {
                                showLoding()
                                getPresenter().zfbPay(it)
                            }
                        } else {
                            ToastUtils.makeText("微信支付")
                        }
                    }
                    bottomPayView.payClose.onClick { mainBottomView.visibility = View.GONE }
                    mainBottomView.addView(bottomPayView)
                }
            }
        }
        if (mainBottomView.visibility == View.GONE) mainBottomView.visibility = View.VISIBLE
    }

    override fun getNewUserInfoSuccess(userBean: UserBean?) {
        hideLoding()
        updateNavInfo()
        userBean?.let {
            when (it.auth) {
                Constant.AttState.ATTSUCESS -> {
                    startActivity(Intent(this@MainActivity, AttMenuActivity::class.java))
                }
                Constant.AttState.ATTING -> {
                    startActivity(Intent(this@MainActivity, AttIngActivity::class.java))
                }
                Constant.AttState.ATTNO -> {
                    startActivity(Intent(this@MainActivity, AttMenuActivity::class.java))
                }
                Constant.AttState.ATTFAIL -> {
                    startActivity(Intent(this@MainActivity, AttFailedActivity::class.java))
                }
            }
        }
    }

    override fun cancelOrderSucess(it: String?) {
        hideLoding()
        mainBottomView.visibility = View.GONE
        mMainTakePicDialog?.dismiss()
        mMainTakePicDialog = null
        mTimer?.cancel()
    }

    //显示站点图片
    override fun showStationPic(datas: List<String>?) {
        hideLoding()
        if (datas == null || datas.isEmpty()) {
            ToastUtils.makeText("该站点暂无图片")
        } else {
            ShowPicDialog(this, datas).show()
        }
    }
    //显示取车前拍照页面
    fun showTakePhotoView() {
        findViewById<LinearLayout>(R.id.upPicAgainLl).visibility = View.GONE
        if (mMainTakePicDialog == null) {
            mMainTakePicDialog = ReportsTakeCarDialog(this)
            mMainTakePicDialog?.setOnDismissListener {
                findViewById<LinearLayout>(R.id.upPicAgainLl)?.visibility = View.VISIBLE
            }
            mMainTakePicDialog?.setOnClickTakePhoto(object : ReportsTakeCarDialog.onClickBtn {
                override fun oNnext() {
                    if (mMainTakePicDialog!!.isOk()) {
                        showLoding()
                       getPresenter().postTakeCarSurface(mMainTakePicDialog!!.imagesUrl)
                    }
                }
                override fun takePic() {
                    picFromWhere = Constant.COMMON.TAKEPIC_TAKECAR_OUT
                    takePicture()
                }
            })
        }
        mMainTakePicDialog?.show()
    }

    var picFromWhere = Constant.COMMON.TAKEPIC_TAKECAR_OUT  //记录在哪里拍的照
    override fun takeSuccess(result: TResult?) {
        result?.let {
            mQiniuUpLoadHelper.filePath = it.image.compressPath
            mQiniuUpLoadHelper?.setUpLoadPicListener(object : QiniuUpLoadHelper.UpLoadPicListener {
                override fun onSuccess(key: String) {
                    when (picFromWhere) {
                        Constant.COMMON.TAKEPIC_TAKECAR_OUT -> {
                            mMainTakePicDialog?.saveImage(it.image.compressPath, key)
                            hideLoding()
                        }
                        Constant.COMMON.TAKEPIC_TAKECAR_IN -> {
                            mReportsInteriorDialog?.addPic(it.image.compressPath, key)
                            hideLoding()
                        }
                        Constant.COMMON.TAKEPIC_BACKCAR_OUT -> {
                            mReportsBackCarDialog?.saveImage(it.image.compressPath, key)
                            hideLoding()
                        }
                    }
                }

                override fun onError(msg: String) {
                    ToastUtils.makeText(msg)
                    hideLoding()
                }
            })
            showLoding()
            mQiniuUpLoadHelper.uploadPic()
        }
    }

    override fun postTakeCarSurfaceSucess(it: OrderResp?) {
        it?.let { OrderControl.updateOrderMianInfo(it) }
        getPresenter().takeCar()
    }

    //    取车成功，内饰报备
    override fun takeCarSucess(it: OrderResp?) {
        hideLoding()
        it?.let {
            OrderControl.updateOrderMianAndVehicleInfo(it)
            setTakeCarViews(it)
        }
        mMainTakePicDialog?.dismiss()
        mMainTakePicDialog = null
        addCarMarker()
        ToastUtils.makeText("取车成功")
    }

    private fun addCarMarker() {
        if (carMaker == null) {
            val markConfig = MarkConfig.viewbuilder()
                    .setMarkView(LayoutInflater.from(this).inflate(R.layout.car_lacation,null))
                    .setLatLng(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()))
                    .build()
            carMaker = mapLoader.addMarkView(bmapView, markConfig) as Marker?
        }
    }

    override fun openDoorSucess(order: OrderResp?) {
        hideLoding()
        ToastUtils.makeText("开门已开启")
        order?.let {
            OrderControl.setCurrentOrder(it)
            if (it.node == Constant.CarState.TAKE_REPORT_INTERIOR) {
                if (mReportsInteriorDialog == null) {
                    mReportsInteriorDialog = ReportsInteriorDialog(this)
                    mReportsInteriorDialog!!.setOnClickTakePhoto(object : ReportsInteriorDialog.onClickTakePhoto {
                        override fun reportsInterior(isDamage: Boolean, dic: String?, pics: ArrayList<String>?) {
                            if (isDamage && dic.isNullOrBlank() && (pics == null || pics.isEmpty())){
                                ToastUtils.makeText("请添加照片或描述")
                                return
                            }
                            showLoding()
                            getPresenter().reportsInterior(isDamage, dic, pics)
                        }

                        override fun takePic() {
                            picFromWhere = Constant.COMMON.TAKEPIC_TAKECAR_IN
                            takePicture()
                        }
                    })
                }
                findViewById<LinearLayout>(R.id.reportsInTimeLl).visibility = View.VISIBLE
                startCountdown(it.expireMillis ?: 1, findViewById<TextView>(R.id.reportsInTime))
                mReportsInteriorDialog?.show()
            }
        }
    }

    override fun closeDoorSucess(it: String?) {
        hideLoding()
        ToastUtils.makeText("开门已关闭")
//        it?.let {
//            OrderControl.updateOrderMianInfo(it)
//        }

    }

    override fun reportsInteriorSucess(it: OrderResp?) {
        hideLoding()
        mReportsInteriorDialog?.dismiss()
        mReportsInteriorDialog = null
        mTimer?.cancel()
        findViewById<LinearLayout>(R.id.reportsInTimeLl).visibility = View.GONE
        it?.let {
            OrderControl.updateOrderMianInfo(it)
        }
    }

    override fun postBackCarSurfaceSucess(it: OrderResp?) {
        it?.let { OrderControl.updateOrderMianInfo(it) }
        getPresenter().backCar()
        mReportsBackCarDialog?.dismiss()
        mReportsBackCarDialog = null
    }

    override fun getCarBreakdownsSucess(it: List<String>?) {
        if (it == null || it.isEmpty()) {
            ToastUtils.makeText("车辆状态异常，请检查")
        } else {
            mBackCarErrorDialog.setErrorInfo(it)
            mBackCarErrorDialog.show()
        }
    }

    override fun backCarSucess(it: OrderResp?) {
        carMaker?.let {
            it.isVisible = false
            carMaker = null
        }
        it?.let {
            OrderControl.updateOrderMianInfo(it)
            setTakeCarViews(it)
        }
    }

    private val handler = MyHandler(this)

    //Kotlin中所有内部类默认是静态的（即嵌套类，不使用inner修饰）.而内部类（使用inner修饰），对象会隐式持有外部类的对象（跟java一样）
    class MyHandler(activity: MainActivity) : Handler() {
        var weakReference = WeakReference(activity)
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MainActivity.SDK_PAY_FLAG -> {
                    // 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    weakReference.get()?.let {
                        it.getPresenter().alipayQuery(msg.data.getString("id"))
                    }
                }
            }
        }
    }

    override fun zfbPay(Orderinfo: PayOrderinfo?) {
        hideLoding()
        val payRunnable = Runnable {
            val alipay = PayTask(this@MainActivity)
            val result = alipay.payV2(Orderinfo?.body, true)
            val msg = Message()
            msg.what = MainActivity.SDK_PAY_FLAG
            val bundle = Bundle()
            bundle.putString("id", Orderinfo?.orderId)
            msg.data = bundle
            msg.obj = result
            handler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    override fun paySuccess(it: Int?) {
        findViewById<FrameLayout>(R.id.mainPayLl).visibility = View.GONE
        findViewById<FrameLayout>(R.id.mainPayingLl).visibility = View.VISIBLE
    }


    //版本更新
    override fun checkVersion(upinfo: CheckVersionResp) {
        if (upinfo.notice!!) return
//        if (!upinfo.notice!!) return
        findViewById<TextView>(R.id.tv_level_hint).visibility = View.VISIBLE
            UpdateVercionDialog.setOnClickAndRes(upinfo.version!!, upinfo.force!!,upinfo.descriptions,object :UpdateVercionDialog.onClickBtn{
                override fun cancelBtn() {
                    if ( upinfo.force) AppManager.finishAllActivity()
                    else UpdateVercionDialog.dismiss()
                }
                override fun sureBtn() {
                    ToastUtils.makeText("下载更新${upinfo.url}")
                    findViewById<TextView>(R.id.tv_level_hint).visibility = View.GONE
                }
            })
        UpdateVercionDialog.show()
    }
    private fun startCountdown(second: Long, viewTime: TextView) {
        mTimer?.cancel()
        var m: Int
        var s1: Int
        var M: String
        var S: String
        mTimer = object : CountDownTimer(second, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                if (viewTime == null) return
                m = (millisUntilFinished / 1000 / 60).toInt()
                s1 = (millisUntilFinished / 1000 % 60).toInt()
                M = if (m < 10) "0$m" else m.toString()
                S = if (s1 < 10) "0$s1" else s1.toString()
                viewTime.text = "$M:$S"
                mMainTakePicDialog?.let {
                    if (it.isShowing) it.startCuntDown("$M:$S")
                }
                mReportsInteriorDialog?.let {
                    if (it.isShowing) it.startCuntDown("$M:$S")
                }
            }
            override fun onFinish() {
                if (OrderControl.getCurrentOrder()?.node == Constant.CarState.TAKE_REPORT_SURFACE)
                    mainBottomView.visibility = View.GONE
                mMainTakePicDialog?.dismiss()
                mMainTakePicDialog = null
                mReportsInteriorDialog?.let {
                    it.dismiss()
                    mReportsInteriorDialog = null
                    findViewById<LinearLayout>(R.id.reportsInTimeLl)?.visibility = View.GONE
                }
            }
        }
        mTimer!!.start()
    }

    override fun onPageSelected(position: Int) {
        nowChoseCarPosition = position
        if (pageSize == position && havePager) {
            choseMaker?.let {
                showLoding()
                getPresenter().getCarList(pager, it.title.toLong())
            }
        }
    }

    /**
     * 地图
     */
    lateinit var mBaiduMap: BaiduMap
    private var phoneAngle: Float = 0f //手机旋转角度
    private var isFirstLocation: Boolean = true//是否第一次定位
    private val mapLoader = MapLoader.getInstance()
    private var isRefreshMaker: Boolean = false//是否重新加载附近站点
    var latlng = LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude())//上次重新加载附近站点位置
    val upStationDistance = 1000 * 5 //大于5公里才更新附近站点

    private fun initMapView() {
        mapLoader.startLocation(this)
        mapLoader.showMyLocation(this)
        bmapView.showZoomControls(false)//不显示缩放按钮
        mBaiduMap = bmapView.map
        mBaiduMap.setOnMarkerClickListener(this)
        if (!mBaiduMap.isMyLocationEnabled)
            mBaiduMap.isMyLocationEnabled = true
        //我的位置先相关设置
        val mylacationIcon = BitmapDescriptorFactory.fromView(LayoutInflater.from(this).inflate(R.layout.view_mylocation, null))
//        val bdMine = BitmapDescriptorFactory.fromBitmap(UIUtils.getBitMap(this,R.mipmap.my_locatio,30, 36))
        val config = MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mylacationIcon
                , Color.parseColor("#194D69FD"), Color.parseColor("#194D69FD"))
        mBaiduMap.setMyLocationConfiguration(config)
        //地图相关设置
        val mMapStatus = MapStatus.Builder()
                .target(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()))
                .overlook(0f)
                .zoom(14f)
                .build()
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus))
        //获取地图中心点坐标，更新附近站点
        mBaiduMap.setOnMapStatusChangeListener(object : MyOnMapStatusChangeListener() {
            override fun onMapStatusChangeStart(p0: MapStatus?, p1: Int) {
                super.onMapStatusChangeStart(p0, p1)
                if (p1 == REASON_GESTURE) {
                    p0?.run {
                        //大于upStationDistance公里才更新
                        if (DistanceUtil.getDistance(LatLng(target.latitude, target.longitude), latlng) > upStationDistance) {
                            isRefreshMaker = true
                        }
                    }
                }
            }

            override fun onMapStatusChangeFinish(mapStatus: MapStatus?) {
                super.onMapStatusChangeFinish(mapStatus)
                if (isRefreshMaker) {
                    mapStatus?.run {
                        mapCenter.animate()
                                .translationYBy(-UIUtils.dip2px(this@MainActivity, 22f).toFloat())
                                .setInterpolator(AnticipateInterpolator())
                                .setDuration(400)
                                .withEndAction {
                                    mapCenter.animate()
                                            .translationYBy(UIUtils.dip2px(this@MainActivity, 22f).toFloat())
                                            .setInterpolator(OvershootInterpolator())
                                            .setDuration(400)
                                            .start()
                                }.start()
                        showLoding()
                        getPresenter().getStations(target.latitude, target.longitude)
                        isRefreshMaker = false
                        latlng = LatLng(target.latitude, target.longitude)
                    }
                }
            }
        })
    }
    //Map添加Marker
    override fun addMarker(carNum: List<StationBean>?) {
        hideLoding()
        if (carNum == null || carNum.isEmpty()) {
            mBaiduMap.clear()
            ToastUtils.makeText("附近暂无站点")
        } else {
            mBaiduMap.clear()
            carNum.forEach {
                var makerView = MyMapmarkerView(this, null)
                makerView.setCarNum(it.vehicleNum ?: 0)
                val extraInfo = Bundle()
                extraInfo.putString(Constant.SP_KEY.STATION_NAME, it.name)
                extraInfo.putString(Constant.SP_KEY.STATION_ADDRESS, it.address)
                extraInfo.putInt(Constant.SP_KEY.STATION_CAR_NUM, it.vehicleNum ?: 0)
                val markConfig = MarkConfig.viewbuilder()
                        .setMarkView(makerView)
                        .setLatLng(LatLng(it.latitude ?: 0.0, it.longitude ?: 0.0))
                        .setTitle(it.id.toString())
                        .setExtraInfo(extraInfo)
                        .build()
                mapLoader.addMarkView(bmapView, markConfig)
            }
        }
        if (carMaker != null){
            carMaker = null
            addCarMarker()
        }
    }

    var choseMaker: Marker? = null
    override fun onMarkerClick(marker: Marker?): Boolean {
        if (marker != carMaker) {
            marker?.let {
                setInfoWindow(it.position)
                choseMaker = it
            }
        }
        return false
    }

    private fun setInfoWindow(latLn: LatLng) {
        val info = LayoutInflater.from(this).inflate(R.layout.window_station, null)
        val offset = UIUtils.dip2px(this, -32f)
        val window = InfoWindow(BitmapDescriptorFactory.fromView(info), latLn, offset,
                InfoWindow.OnInfoWindowClickListener {
                    choseMaker?.let {
                        showLoding()
                        getPresenter().getStationPic(it.title)
                    }
                })
        mBaiduMap.showInfoWindow(window)
    }

    //定位成功返回坐标
    override fun onLocationSuccess(bdLocation: BDLocation?) {
        bdLocation?.run {
            carMaker?.let { it.position = LatLng(latitude, longitude) }
            CommonUtils.savaLatLon(latitude, longitude)
            updateMyLocation()
            //
//            LogUtils.d("$latitude||$longitude")
        }
        if (isFirstLocation) {
            removeToMyLocation()
            showLoding()
            getPresenter().getStations(CommonUtils.getLatitude(), CommonUtils.getLongitude())
            isFirstLocation = false
        }
    }

    //移动当前位置到屏幕中心
    private fun removeToMyLocation() {
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude())))
        if (DistanceUtil.getDistance(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()), latlng) > upStationDistance) {
            isRefreshMaker = true
        }
    }

    private var locationShowErrorTime: Long = 0
    //定位失败
    override fun onLocationFail(bdLocation: BDLocation?) {
        //定位失败30-32秒显示一次
        if (System.currentTimeMillis() - locationShowErrorTime > 30 * 1000) {
            locationShowErrorTime = System.currentTimeMillis()
            ToastUtils.makeText("定位失败，请检查网络以及GPS")
        }
    }

    //手机方向改变
    override fun onOrientationChanged(x: Float) {
        phoneAngle = x
        updateMyLocation()
    }

    //更新自己的位置
    private fun updateMyLocation() {
        mapLoader.setLocationDirectationMarker(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()), phoneAngle, mBaiduMap)
    }

    //显示选车页面 别和我说用viewPager更简单，我只能告诉你不止一个坑
    private var starionName = ""
    private var starionAddress = ""
    private var distance = 0
    private var pageSize = 0
    private val linearLayoutManager by lazy { LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) }
    private var mChoseCarRecyclerAdapter: ChoseCarRecyclerAdapter? = null
    private val datas: MutableList<CarInfoBean?> = ArrayList()
    private var havePager = false
    private var pager = 1
    private var nowChoseCarPosition = 0
    override fun initChoseCarView(carDatas: CarListResp?) {
        hideLoding()
        if (carDatas?.list == null || carDatas.list.isEmpty()) {
            if (havePager) {
                havePager = false
                return
            }
            ToastUtils.makeText("该站点暂无可用车辆")
            return
        }
        if (carDatas.list.size == carDatas.pageSize) {
            havePager = true
            pager++
        } else havePager = false
        datas.addAll(carDatas.list)
        if (mChoseCarRecyclerAdapter == null) {
            mChoseCarRecyclerAdapter = ChoseCarRecyclerAdapter(datas)
            choseCarView.choseCarRecyclerView.layoutManager = linearLayoutManager
            choseCarView.choseCarRecyclerView.adapter = mChoseCarRecyclerAdapter
            val mScalableCardHelper = ScalableCardHelper(this)
            mScalableCardHelper.attachToRecyclerView(choseCarView.choseCarRecyclerView)
        } else {
            mChoseCarRecyclerAdapter!!.notifyDataSetChanged()
        }
        pageSize = datas.size - 1
        choseCarView.carLocation.text = starionName
        choseCarView.carLocationDetail.text = starionAddress
        choseCarView.carDistance.text = "${distance}m"
        choseCarView.setOnTouchListener { v, event -> true }
        choseCarView.visibility = View.VISIBLE
        choseCarView.choseCarUse.onClick {
            showLoding()
            getPresenter().createOrder(datas[nowChoseCarPosition]!!.id)
        }
        choseCarView.choseCarCancel.onClick {
            choseCarView.visibility = View.GONE
        }
    }

    //侧边栏点击事件
    private val doubleClick = View.OnClickListener { v ->
        drawer_layout.closeDrawer(Gravity.START)
        drawer_layout.postDelayed({
            when (v.id) {
                R.id.iv_headimg -> startActivity(Intent(this@MainActivity, MyCenterActivity::class.java))
                R.id.ll_nav_order ->startActivity(Intent(this@MainActivity, OrderCenterActivity::class.java))
                R.id.ll_nav_att -> {
                    showLoding()
                    getPresenter().getNewUserInfo()
                }
                R.id.ll_nav_connection -> ToastUtils.makeText("click four")
            }
        }, 200)
    }

    //初始化侧边栏和点击事件
    fun initClickAndNav() {
        updateNavInfo()
        nav_view.tv_level.text = "版本号 " + AppUtils.getVersionName(this)
        nav_view.ll_level.onClick {
            if(nav_view.tv_level_hint.visibility == View.VISIBLE) getPresenter().checkVersion(AppUtils.getVersionName(this@MainActivity)!!,true)
        }
        nav_view.iv_headimg.setOnClickListener(doubleClick)
        nav_view.ll_nav_order.setOnClickListener(doubleClick)
        nav_view.ll_nav_att.setOnClickListener(doubleClick)
        nav_view.ll_nav_connection.setOnClickListener(doubleClick)
        nav.onClick { openDrawer() }
        toMyLocation.onClick { removeToMyLocation() }
        BtnUseCar.onClick {
            if (choseMaker != null) {
                if (choseMaker!!.extraInfo.getInt(Constant.SP_KEY.STATION_CAR_NUM) > 0) {
                    starionName = choseMaker!!.extraInfo.getString(Constant.SP_KEY.STATION_NAME)
                    starionAddress = choseMaker!!.extraInfo.getString(Constant.SP_KEY.STATION_ADDRESS)
                    distance = DistanceUtil.getDistance(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude()), choseMaker!!.position).toInt()
                    datas?.clear()
                    choseCarView.choseCarRecyclerView.scrollToPosition(0)
                    pager = 1
                    showLoding()
                    getPresenter().getCarList(pager, choseMaker!!.title.toLong())
                } else ToastUtils.makeText("该站点暂无可用车辆")
            } else ToastUtils.makeText("请先选择站点")
        }
        goAtt.onClick {
            showLoding()
            getPresenter().getNewUserInfo()
        }
        refreshMap.onClick {
            showLoding()
            getPresenter().getDoingOrder()
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(LatLng(CommonUtils.getLatitude(), CommonUtils.getLongitude())))
            isRefreshMaker = true
        }
    }

    //打开侧边栏
    fun openDrawer() {
        drawer_layout.openDrawer(Gravity.LEFT)
    }

    //设置状态栏
    private fun setStatuBar() {
        MyStatusBarUtil.setColorForSwipeBackDrawerLayout(this, resources.getColor(R.color.white), 0)
        MyStatusBarUtil.setLightMode(this)
    }

    override fun onEvent(event: EventMap.BaseEvent) {
        if (event is EventMap.UpUserInfoEvent) {
            updateNavInfo()
        }
    }

    private fun updateNavInfo() {
        UserControl.getCurrentUser()?.let {
            GlideUtils.loadImage(this, it.icon, nav_view.iv_headimg, R.mipmap.deafult_head)
            if (it.mobile?.length!! > 7) nav_view.tv_username.text = it.mobile.replaceRange(3, 7, "****")
            when (it.auth) {
                Constant.AttState.ATTING -> {
                    attFailReason.text = "身份认证正在进行中！"
                    goAtt.text = "去查看"
                    attFail.visibility = View.VISIBLE
                }
                Constant.AttState.ATTNO -> {
                    attFailReason.text = "请先进行身份认证！"
                    goAtt.text = "去认证"
                    attFail.visibility = View.VISIBLE
                }
                Constant.AttState.ATTSUCESS -> {
                    attFail.visibility = View.GONE
                }
                Constant.AttState.ATTFAIL -> {
                    attFailReason.text = "身份认证审核失败! "
                    goAtt.text = "重新认证"
                    attFail.visibility = View.VISIBLE
                }

            }
        }
    }

    override fun onResume() {
        super.onResume()
        bmapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        bmapView.onPause()
    }

    override fun onDestroy() {
        mapLoader.stopLocation()
        mapLoader.recycle()
        if (mMainTakePicDialog != null) {
            mMainTakePicDialog?.dismiss()
            mMainTakePicDialog = null
        }
        super.onDestroy()
        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }
        bmapView.onDestroy()
        // 当不需要定位图层时关闭定位图层
        mBaiduMap.isMyLocationEnabled = false
        mQiniuUpLoadHelper?.let {
            it.setCancle(true)
            it.setUpLoadPicListener(null)
        }
    }

    override fun onBackPressed() {
        if (choseCarView.visibility == View.VISIBLE) {
            choseCarView.visibility = View.GONE
            return
        }
        if (null == toast?.getView()?.getParent()) {
            toast?.show()
        } else {
            super.onBackPressed()
        }
    }

}